package control;

import java.util.ArrayList;

import model.Alive;
import model.Element;
import model.Ticking;

public class Ticker<T extends Alive> extends ArrayList<T> implements Ticking{
	protected ArrayList<T> toAdd = new ArrayList<T>();
	protected ArrayList<T> toRemove = new ArrayList<T>();
	
	public synchronized boolean add(T added){
		return toAdd.add(added);
	}
	
	public synchronized boolean remove(T removed){
		return toRemove.remove(removed);
	}
	
	public synchronized void flushAdded(){
		addAll(toAdd);
		toAdd.clear();
	}
	
	public synchronized void flushRemoved(){
		removeAll(toRemove);
		toRemove.clear();
	}

	public synchronized void tick() {
		for(Alive a : this){
			a.tick();
			if(!a.isAlive()){
				remove(a);
			}
		}
		flushRemoved();
		flushAdded();
	}
}
